package sprite;

import java.awt.DisplayMode;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;

import javax.swing.ImageIcon;


import screenmanager.ScreenManager;
import animation.Animation;

public class BuckySprite {

	
	public static void main(String[] args) {
		BuckySprite b = new BuckySprite();
		b.run();
	}
	
	private Animation a;
	private ScreenManager s;
	private Image bg;
	private Sprite sprite;
	
	private static final DisplayMode modes[] = {
		new DisplayMode(800, 600, 32, 0),
		new DisplayMode(800, 600, 24, 0),
		new DisplayMode(800, 600, 16, 0),
		new DisplayMode(640, 480, 32, 0),
		new DisplayMode(640, 480, 24, 0),
		new DisplayMode(640, 480, 16, 0),
		new DisplayMode(1024, 768, 16, 0),
	};
	
	public void loadImages(){
		bg = new ImageIcon("img/bg.jpg").getImage();
		Image f1 = new ImageIcon("img/f1.jpg").getImage();
		Image f2 = new ImageIcon("img/f2.jpg").getImage();
		
		a = new Animation();
		a.addScene(f1, 250);
		a.addScene(f2, 250);
		
		sprite = new Sprite(a);
		sprite.setVelocityX(0.3f);
		sprite.setVelocityX(0.3f);
	}
	
	public void run(){
		s = new ScreenManager();
		try{
			DisplayMode dm = s.findFirstCompatibleMode(modes);
			s.setFullScreen(dm);
			loadImages();
			movieLoop();
		}finally{
			s.restoreScreen();
		}
	}
	public void movieLoop(){
		long startingTime = System.currentTimeMillis();
		long cumTime = startingTime;
		while(cumTime - startingTime < 6000){
			long timePassed = System.currentTimeMillis() - cumTime;
			cumTime += timePassed;
			
			//a.update(timePassed);
			update(timePassed);
			
			Graphics2D g = s.getGraphics();
			draw(g);
			g.dispose();
			s.update();
			
			try{
				Thread.sleep(20);
			}catch(Exception e){}
		}
	}
	
	
	public void draw(Graphics g){
		g.drawImage(bg,0,0,null);
		//g.drawImage(a.getImage(),0,0,50,50,null);
		g.drawImage(sprite.getImage(),Math.round(sprite.getX()),Math.round(sprite.getY()),null);
	}
	
	public void update(long timePassed){
		if(sprite.getX() < 0){
			sprite.setVelocityX(Math.abs(sprite.getVelocityX()));
		}else if(sprite.getX() + sprite.getWidth() >= s.getWidth()){
			sprite.setVelocityX(-Math.abs(sprite.getVelocityX()));
		}
		
		if(sprite.getY() < 0){
			sprite.setVelocityY(Math.abs(sprite.getVelocityY()));
		}else if(sprite.getY() + sprite.getHeight() >= s.getHight()){
			sprite.setVelocityY(-Math.abs(sprite.getVelocityY()));
		}
		
		sprite.update(timePassed);
	}
}
